

import { Service } from 'egg';

const querystring = require('querystring');
import Encrypt from '../../utils/crypto';
import baseCookie,{randomUserAgent,_request} from '../../utils/init';


export default class Mequest extends Service {
    
    


    /**
     * 
     * @param url 
     * @param method 
     * @param data 
     * @param cookie 
     */
    public async createWebAPIRequest(url,method,data,cookie?):Promise<{body:any,cookie:string}> {

        console.log('data',data)

        cookie = cookie || this.ctx.request.header.cookie || ''
    
        let reg = /__csrf=([a-zA-Z0-9]+);/
        // let reg = /_csrf=[^(;|$]+g/

        if(cookie.match(reg)){
            data.csrf_token = cookie.match(reg)[1]
        }else{
            data.csrf_token = ""
        }
        const proxy = cookie.split("__proxy__")[1];
        cookie = cookie.split("__proxy__")[0];
        const cryptoreq = Encrypt(data);
        const options = {
            url:this.config.baseUrl+url,
            method,
            headers:{
                Accept: "*/*",
                "Accept-Language": "zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4",
                Connection: "keep-alive",
                "Content-Type": "application/x-www-form-urlencoded",
                Referer: "http://music.163.com",
                Host: "music.163.com",
                Cookie: baseCookie + (cookie ? "; " : "") +  cookie,
                "User-Agent": randomUserAgent()
            },
            body:querystring.stringify({
                params:cryptoreq.params,
                encSecKey:cryptoreq.encSecKey
            }),
            proxy
        }
        console.log(`[request] ${options.method} ${options.url} proxy:${options.proxy}`)

        const result = await _request(options);
        return result;
    }

    public async createRequest(url,method,data){
        const options:any = {
            url,
            method,
            headers: {
                Referer: "http://music.163.com",
                Cookie: "appver=1.5.2",
                "Content-Type": "application/x-www-form-urlencoded",
                "User-Agent": randomUserAgent()
            }
        }
        if(method.toLowerCase() === 'post'){
            options.body = data;
        }
        return await _request(options)
    }

    public   parseCookie (cookies){

        const list = cookies.map(cookie=>{
            let res:any ={},options:any = {}
           cookie.split(';').forEach((ckinfoStr,index)=>{
               let ckInfos = ckinfoStr.split('=');  
                if(index === 0){
                    res.name = ckInfos[0];
                    res.value = ckInfos[1]
                }else{
                    options[ckInfos[0]] = ckInfos[1]
                }
           });
           options.Path = '/';
           return {
               cookie:res,options
           }
        })
        return list;
    }
}

